<template>
	<div class="content" v-show="!callCode">
		<!-- 组件设置 注释掉 基础信息、自助提交、视频坐席标题-->
		<!-- <my-step style="margin-top: 20px;width: 100%;" :current="2"></my-step> -->
		<div class="line"></div>
		<img src="../../static/image/kefu.png" style="width: 60px;height: 60px;margin-top: 20px" />
		<div class="setting" v-clickoutside="hideSetting">
			<div class="settingImg"><img src="../../static/image/setting.png" @click="showSettingContent"/></div>
			<div class="settingContent" v-show="isShowSettingContent">
				<div class="audioContent" @click="selectMode('audio')">
					<img src="../../static/image/audioImg.png" v-show="mode != 'audio'" />
					<img src="../../static/image/audioSelected.png" v-show="mode == 'audio'" />
					<span :class="[mode == 'audio' ? 'isActive' : '']">{{ $t('ivcs.voiceCall') }}</span>
				</div>
				<div class="horizontalLine"></div>
				<div class="videoContent" @click="selectMode('video')">
					<img src="../../static/image/videoImg.png" v-show="mode != 'video'" />
					<img src="../../static/image/videoSelected.png" v-show="mode == 'video'" />
					<span :class="[mode == 'video' ? 'isActive' : '']">{{ $t('ivcs.videoCall') }}</span>
				</div>
			</div>
		</div>
		<Dropdown class="select" trigger="click" @on-click="selectBizScenario" v-if="!inviteCode">
			<Button class="chooseBtn">
				{{ type }}
			</Button>
			<DropdownMenu slot="list">
				<DropdownItem :name="item.value" :selected="selectBizScenarioName === item.value" v-for="(item, index) in bizScenarioList" :key="index">{{ item.value }}</DropdownItem>
			</DropdownMenu>
		</Dropdown>
		<div class="btn defaultbackColor" @click.prevent="videochat(0)" v-if="!inviteCode">{{ $t('ivcs.callagent') }}</div>
		<div class="btn defaultbackColor" style="margin-top: 20px" @click.prevent="imchat()" v-if="!inviteCode">IM呼叫</div>
		<!-- 同屏入口 -->
		<div class="btn defaultbackColor" @click="screensyncchat" style="margin-top: 20px;" v-if="!inviteCode">{{ $t('ivcs.screensync') }}</div>
		<div class="btn defaultbackColor" style="margin-top: 20px" @click="componentSettingBtnClick">{{ $t('ivcs.componentSetting') }}</div>

		<!-- videosetting  原视频设置注释了，改成组件设置
		<div class="btn defaultbackColor" style="color:rgba(100,202,171,1);background: white;border:1px solid rgba(100,202,171,1);margin-top: 20px" @click="showsetting = true">{{ $t('ivcs.videosetting') }}</div>  -->

		<settings style="margin-top: 10px" v-show="showsetting" @close="showsetting = false"></settings>

		<!--<div>请选择坐席技能</div>-->

		<!--<Select v-model="category" class="select">-->
		<!--<Option v-for="item in categoryList" :value="item.value" :key="item.value">{{ item.label }}</Option>-->
		<!--</Select>-->

		<div class="toast" v-show="isShowToast" v-if="!inviteCode">
			<div class="toastcontent">
				<div class="toastagent">
					<span>{{ $t('ivcs.agentOnCamera') }}</span>
					<i-switch v-model="agentFaceStatus" @on-change="agentShowFace" />
				</div>
				<div class="toastcustomer">
					<span>{{ $t('ivcs.meOnCamera') }}</span>
					<i-switch v-model="customerFaceStatus" @on-change="customerShowFace" />
				</div>
				<div class="toasttip" v-show="isShowToastTip">
					<img src="../../static/image/exclame.png" alt="" />
					<span>{{ $t('ivcs.outOfMirror') }}</span>
				</div>
			</div>
			<div class="toastfooter">
				<span class="cancel" @click="cancel">{{ $t('ivcs.No') }}</span>
				<span class="preserve" @click="preserve">{{ $t('ivcs.save') }}</span>
			</div>
		</div>
		<div :class="{ backDemon: isShowToast }"></div>
		<!-- 组件设置 -->
		<component-setting v-if="dialogVisible" :dialogVisible="dialogVisible" @cancel="cancelComponentSettingBtn" @ok="determineBtn"></component-setting>
		<div class="invite-code" v-if="!inviteCode"
			><span>访客角色：</span>
			<!-- <Input v-model="customerRole" :maxlength="roleInput" placeholder="请输入访客角色" style="width: 250px"></Input> -->
			<Select v-model="customerRole" style="width:250px">
				<Option v-for="item in roleList" :value="item.name" :key="item.name">{{ item.name }}</Option>
			</Select>
		</div>
		<div class="invite-code"><span>业务流水号：</span> <Input v-model="businessflowId" placeholder="请输入业务流水号" style="width: 250px"></Input> </div>
		<div class="invite-code"><span>呼叫优先级：</span> <Input v-model="customerLevel" placeholder="请输入正整数数值" type="number" style="width: 250px"></Input> </div>
		<div class="label_view" v-if="!inviteCode"
			><span>业务标签：</span>
			<!-- <Input v-model="customerRole" :maxlength="roleInput" placeholder="请输入访客角色" style="width: 250px"></Input> -->
			<Select v-model="label" style="width:250px">
				<Option v-for="item in labelList" :value="item.id" :key="item.name">{{ item.name }}</Option>
			</Select>
		</div>
		<div class="request_setting_view" v-if="!inviteCode"
			><span>派工方式:</span>
			<RadioGroup v-model="requestWay" type="button" button-style="solid" @on-change="onChange">
				<Radio label="不指定"></Radio>
				<Radio label="指定坐席"></Radio>
				<Radio label="指定技能组"></Radio>
			</RadioGroup>
		</div>
		<div v-show="requestWay === '指定坐席'" style="margin-bottom: 30px"><span>指定坐席工号：</span> <Input v-model="callAgentId" placeholder="请输入指定坐席工号" style="width: 250px"></Input> </div>
		<div id="select-group" v-show="requestWay === '指定技能组'" style="margin-bottom: 30px">
			<span>可选分组：</span>
			<Select v-model="selectGroups" multiple style="width:250px" @on-change="handleSelectChange">
				<Option v-for="item in groupList" :value="item.id" :key="item.id">{{ item.name }}</Option>
			</Select>
			<div style="width:100%; text-align: left; height: 80px; line-height: 80px;">呼叫分组链： <Input v-model="callGroups" type="textarea" readonly style="width: 250px"/></div>
		</div>
		<!-- 邀请码 -->
		<div class="invite-code" v-if="inviteCode"><span>邀请码：</span> <Input v-model="inviteCode" placeholder="请输入邀请码" style="width: 250px"></Input> </div>
		<div class="btn defaultbackColor" style="margin-top: 20px" @click="joinsession" v-if="inviteCode">加入会话</div>
		<!-- <div class="btn defaultbackColor" style="margin-top: 20px" @click="inviteVistors">邀请访客</div> -->
		<invite-members :roleList="roleList" v-if="showinvteModelView" :showinvteModelView="showinvteModelView" @colseCancel="colseCancel" @linkGeneration="linkGeneration" :sessionId="sessionId" :createInviteCode="createInviteCode"></invite-members>
		<Spin fix v-if="loadingStatus">
			<Icon type="load-d" class="demo-spin-icon-load"></Icon>
			<div>呼叫中</div>
		</Spin>
		<!-- 选项判断 -->
		<options-page v-if="cmdId" :cmdId="cmdId" :clientId="clientId" :showOptions="true" :optionsData="optionsData" :responseMakeChoice="responseMakeChoice" @confirmOptions="cmdId = ''"></options-page>
		<black-user-error v-if="isBlacklistedUserShow" :content="alertContent" contentWidth="150" @close="onMediaError"></black-user-error>
	</div>
</template>

<script>
import Settings from './Settings';
// import MyStep from './MyStep';
import { getAllBizScenario, createInviteVisitorsCode, getScenariosRoles, getIsRobotAgent, getBizLabels, getScenariosBindGroups } from '../api/api';
import _ from 'lodash';
import ComponentSetting from './ComponentSetting.vue';
import InviteMembers from './InviteMembers.vue';
import OptionsPage from './OptionsPage.vue';
import BlackUserError from './BlackUserError.vue';
export default {
	name: 'Start',
	components: { /*  MyStep, */ Settings, ComponentSetting, InviteMembers, OptionsPage, BlackUserError },
	data() {
		return {
			canCall: false, // 可以呼叫
			selectCallGroups: [], // 呼叫的技能组
			selectGroups: [], // 选择技能组
			groupList: [], // 技能组列表
			labelList: [], // 呼叫的标签列表
			label: '', // 呼叫的标签id
			requestWay: '不指定',
			isBlacklistedUserShow: false,
			alertContent: '',
			showsetting: false,
			selectBizScenarioName: '', //选择的业务场景名
			type: this.$t('ivcs.agenttype'),
			bizScenarioList: [],
			isShowSettingContent: false,
			mode: 'video', //呼叫的模式，默认是视频呼叫
			agentFaceStatus: true, //默认视频通话
			customerFaceStatus: true, //默认视频通话
			isShowToast: false, // 显示选择双方的模式
			isShowToastTip: false,
			dialogVisible: false,
			showSwitch: false,
			inviteCode: '', // Pagelink文件下面的Login.vue 登录组件带过来的值，
			showinvteModelView: false, // 是否显示邀请访客的弹框
			sessionId: '', // 邀请访客加入的sessionId
			customerRole: '',
			roleInput: 8,
			inviteUserName: '', // 游客名
			createInviteCode: '', // 访客自己产生的inviteCode
			loadingStatus: false, //是否显示loading
			businessflowId: '', // 业务流水号
			cmdId: '', // 选项判断cmdId
			clientId: '', // 发送选项判断的clientId
			optionsData: [], // 选项判断的数据
			callAgentId: '', // 呼叫指定坐席工号
			roleList: [], // 角色列表
			customerLevel: null, // 呼叫优先级
			callCode: null // 呼叫码
		};
	},
	computed: {
		callGroups() {
			// 使用数组的 map 方法将所有 name 属性提取并组合成一个字符串
			return this.selectCallGroups.map(item => item.name).join(', ');
		}
	},
	mounted() {
		//页面刷新的事件的处理，登入登出
		window.onbeforeunload = function(e) {
			console.log('onbeforeunload', e);
			//离开房间
			e = e || window.event;
			//兼容IE8和Firefox 4之前的版本
			if (e) {
				e.returnValue = '关闭提示';
			}
			// Chrome, Safari, Firefox 4+, Opera 12+ , IE 9+
			if (!this.inviteCode) {
				return '';
			}
		};
		//  刷新页面自动挂断
		window.onunload = function(e) {
			console.log('onunload', e);
			ivcsCustomer.hangup('page-reload');
		};
		let query = this.$route.query;
		console.log('query', query);
		this.inviteCode = query.inviteCode;
		this.org = query.org;
		this.callCode = query.callCode;

		if (this.inviteCode && this.org) {
			// 被邀请进入的用户
			this.inviteUserName = '游客' + Math.floor(Math.random() * 100 + 99);
			this.initWidget(this.inviteUserName, false);
			this.joinsession(); // 自动加入会话
		} else if (query.callCode) {
			//  呼叫码呼叫
			this.customerRole = '访客';
			let isScreenSync = query.screenSync ? query.screenSync : false;
			let callType = query.callType ? query.callType : 'video';
			let receiveType = query.receiveType ? query.receiveType : 'video';
			this.initWidget(
				'',
				true,
				() => {
					this.requestSession(callType, receiveType, true, true, isScreenSync, null, this.callCode);
				},
				e => {
					console.log('init connect e', e);
				}
			);
		} else {
			// 正常呼叫
			this.initData();
			this.initWidget();
			this.getAllBizScenario();
			this.getLabels();
		}
	},
	methods: {
		/**
		 * 页面加载初始化
		 */
		initData() {
			if (!sessionStorage.getItem('bitrate')) {
				sessionStorage.setItem('bitrate', 512);
			}
			if (!sessionStorage.getItem('videocodec')) {
				sessionStorage.setItem('videocodec', 'h264');
			}
			if (!sessionStorage.getItem('myresoultion')) {
				sessionStorage.setItem(
					'myresoultion',
					JSON.stringify({
						width: 640,
						height: 480
					})
				);
			}
			sessionStorage.removeItem('bizScenarioName');
			this.type = this.$t('ivcs.agenttype');
		},
		handleSelectChange(value) {
			this.selectGroups = value;
			this.selectCallGroups = value
				.map(id => {
					const matchingObject = this.groupList.find(obj => obj.id === id);
					return matchingObject ? { id: matchingObject.id, name: matchingObject.name } : null;
				})
				.filter(Boolean);
			console.log('handleSelectChange', value, this.selectCallGroups);
		},
		/**
		 * 获取所有的标签
		 */
		getLabels() {
			return new Promise((resolve, reject) => {
				getBizLabels()
					.then(s => {
						console.log('getBizLabels success', s);
						if (s?.data?.code === 200) {
							this.labelList = s?.data?.data;
							this.labelList.unshift({
								id: '',
								name: '无'
							});
						} else {
							this.$Message.error('获取标签列表失败');
						}
						resolve(s);
					})
					.catch(e => {
						console.log('getBizLabels error', e);
						this.$Message.error('获取标签列表失败');
						reject(e);
					});
			});
		},

		/**
		 * 切换派工方式
		 */
		onChange(value) {
			console.log(value);
			this.requestWay = value;
			this.callAgentId = '';
			this.selectGroups = [];
		},
		/**
		 * 黑名单错误
		 */
		onMediaError() {
			this.isBlacklistedUserShow = false;
			this.backLogin();
		},
		/**
		 * 根据业务场景id获取所有的访客角色
		 * @param {string} scenId
		 */
		getScenariosRolesWithId(scenId) {
			this.$Spin.show();
			return new Promise((resolve, reject) => {
				getScenariosRoles(scenId)
					.then(resp => {
						console.log('getScenariosRoles result', resp);
						if (resp.data && resp.data.data && resp.data.data.length > 0) {
							this.roleList = resp.data.data;
							console.log('getScenariosRoles roleList', this.roleList);
							sessionStorage.setItem('roleList', JSON.stringify(this.roleList));
							resolve(resp.data.data);
						} else {
							this.$Message.error('当前业务场景下无角色');
							reject();
						}
						this.$Spin.hide();
					})
					.catch(e => {
						this.$Message.error('获取业务场景下角色失败');
						reject(e);
						this.$Spin.hide();
					});
			});
		},

		/**
		 * 获取业务场景下绑定的分组
		 * @param {string} scenId
		 */
		getScenariosBindGroups(scenId) {
			this.$Spin.show();
			return new Promise((resolve, reject) => {
				getScenariosBindGroups(scenId)
					.then(resp => {
						console.log('getScenariosBindGroups result', resp);
						if (resp.data.details && resp.data.details.agentGroup) {
							this.groupList = resp.data.details.agentGroup.map(item => {
								return {
									name: item.name,
									id: item.id
								};
							});
							resolve(this.groupList);
						} else {
							this.$Message.error('当前业务场景下无绑定分组');
							reject();
						}
						this.$Spin.hide();
					})
					.catch(e => {
						this.$Message.error('获取业务场景下绑定分组失败');
						reject(e);
						this.$Spin.hide();
					});
			});
		},
		cancel() {
			if (!this.agentFaceStatus && !this.customerFaceStatus) {
				this.isShowToastTip = true;
				return;
			}
			this.isShowToast = false;
		},
		preserve() {
			if (!this.agentFaceStatus && !this.customerFaceStatus) {
				this.isShowToastTip = true;
				return;
			}
			this.isShowToast = false;
		},
		agentShowFace(status) {
			this.agentFaceStatus = status;
			console.log('agentFaceStatus', status);
		},
		customerShowFace(status) {
			this.customerFaceStatus = status;
			console.log('customerShowFace', status);
		},
		hideSetting() {
			this.isShowSettingContent = false;
		},
		selectMode(value) {
			this.mode = value;
			// 视频模式下。并且非邀请码加入可以设置访客和坐席的音视频模式
			if (this.mode == 'video' && !this.inviteCode) {
				this.isShowToast = true;
			}
			this.hideSetting();
			console.log('mode', this.mode);
		},
		showSettingContent() {
			this.isShowSettingContent = true;
		},

		/**
		 * 获取当前机构下的所有启用的业务场景
		 */
		getAllBizScenario() {
			var self = this;
			getAllBizScenario()
				.then(function(resp) {
					if (resp.data && resp.data.scenList) {
						_.forEach(resp.data.scenList, function(item) {
							self.bizScenarioList.push({
								value: item.name,
								label: item.name,
								id: item.id
							});
						});
					}
					console.log('get all bizScenarioList result', resp, self.bizScenarioList);
				})
				.catch(error => {
					console.log('getAllBizScenario error', error);
					if (error && error.response) {
						let response = error.response;
						this.requestError(response);
					}
				});
		},

		requestError(response) {
			if (response && response.data && response.data.code === '1104') {
				this.$Message.error('当前账号已失效');
			} else if (response && response.data && response.data.code === '1401') {
				this.$Message.error('操作数据库失败');
			} else if (response && response.data && response.data.code === '1301') {
				this.$Message.error('提交数据错误');
			} else if (response && response.data && response.data.code === '1101') {
				this.$Message.error('账号认证失败，请重新登录');
				this.$router.push('/');
			} else if (response && response.data && response.data.code === '1102') {
				this.$Message.error('请求被拒绝，请重新登录');
				this.$router.push('/');
			} else if (response && response.data && response.status === 401) {
				this.$Message.error('账号失效，请重新登录');
				this.$router.push('/');
			}
		},

		/**
		 * 是否是机器人坐席
		 * @param {string} name
		 * @param {string} org
		 */
		isRobotAgent(name, org) {
			return new Promise((resolve, reject) => {
				getIsRobotAgent(name, org)
					.then(resp => {
						console.log('getIsRobotAgent success', resp);
						if (resp?.data?.isRobot === 'true' || resp?.data?.isRobot === true) {
							resolve(1);
						} else {
							resolve(0);
						}
					})
					.catch(error => {
						console.log('getIsRobotAgent error', error);
						reject(error);
					});
			});
		},

		selectBizScenario(value) {
			console.log('selectBizScenario', value);
			this.type = value;
			this.selectBizScenarioName = value;
			this.bizScenarioList.forEach(item => {
				console.log('item', item);
				if (item.value === value) {
					sessionStorage.setItem('bizScenarioName', value);
					sessionStorage.setItem('service', item.id);
					this.getScenariosRolesWithId(item.id);
					this.getScenariosBindGroups(item.id);
				}
			});
			console.log(sessionStorage.getItem('bizScenarioName'), sessionStorage.getItem('service'));
		},

		/**
		 * im呼叫
		 */
		async imchat() {
			console.log('callAgentId', this.callAgentId);
			if (!this.canCall) {
				console.log('isConnect');
				return;
			}
			if (!this.customerRole) {
				this.$Message.error('呼叫时请填写访客角色！');
				return;
			}
			if (sessionStorage.getItem('bizScenarioName')) {
				this.loadingStatus = true;
				if (this.callAgentId) {
					try {
						const isRobot = await this.isRobotAgent(this.callAgentId, localStorage.getItem('org'));
						console.log('isRobot', isRobot);
						if (isRobot) {
							this.$Message.error('IM呼叫不支持呼叫机器人坐席角色');
							this.loadingStatus = false;
							return;
						}
						let callAgentProperty = 'human';
						this.requestSession('im', callAgentProperty, true, true, false, this.callAgentId);
					} catch (error) {
						console.log('isRobotAgent error', error);
						this.loadingStatus = false;
						this.$Message.error('请求异常，请稍后再试！');
						return;
					}
				} else {
					let callAgentProperty = 'human';
					this.requestSession('im', callAgentProperty, true, true, false, this.callAgentId);
				}
			} else {
				this.$Message.error(this.$t('input.chooseServerType'));
			}
		},

		/**
		 * 监听到组件内部执行访客挂断
		 */
		onCustomerAutoHangup() {
			ivcsCustomer.onCustomerAutoHangup(info => {
				console.log(info, 'onCustomerQuitSession data');
				sessionStorage.setItem('username', '');
				sessionStorage.setItem('idcard', '');
				sessionStorage.setItem('mobile', '');
				sessionStorage.setItem('address', '');
				sessionStorage.setItem('selfimg', '');
				sessionStorage.setItem('idcardFront', '');
				sessionStorage.setItem('idcardBack', '');
				sessionStorage.setItem('bankImg', '');
				sessionStorage.setItem('company', '');
				sessionStorage.setItem('category', '');
				sessionStorage.setItem('gender', '');
				if (!info || ['rated', 'the specified agent is rejected', 'system-error', 'ringingTimeout', 'cancel', 'rejected', 'notfound', 'offday', 'offtime', 'scenariodisabled', 'not found others', 'labelsDoNotMatch', 'groupsDoNotMatch', 'hangup'].includes(info) || typeof info === 'object') {
					console.log('destroy widget###');
					ivcsCustomer.destroy();
					if (this.inviteCode) {
						return;
					}
				}
				this.backLogin();
			});
		},

		backLogin() {
			let query = this.$route.query;
			let virtualAgentType = query.virtualAgentType;
			let qv = '';
			if (virtualAgentType) {
				if (virtualAgentType !== 'registered' && virtualAgentType !== 'unregistered') {
					virtualAgentType = 'registered';
				}
				qv = 'virtualAgentType=' + virtualAgentType;
			}
			this.$router.push('/' + '?' + qv);
		},

		// 收到邀请访客的消息
		onInviteCustomer() {
			ivcsCustomer.onInviteCustomer((sessionId, bizId, org, token) => {
				console.log(sessionId, 'onInviteCustomer', bizId, org, token);
				if (bizId) {
					sessionStorage.setItem('service', bizId);
				}
				if (org) {
					localStorage.setItem('org', org);
				}
				token && localStorage.setItem('customer_token', token);
				this.sessionId = sessionId;
				this.showinvteModelView = true;
				setTimeout(() => {
					let box = document.querySelector('.ivu-modal-wrap');
					console.log(box);
					box && box.setAttribute('style', 'z-index:999999999');

					let shadow = document.querySelector('.ivu-modal-mask');
					console.log(shadow);
					shadow && shadow.setAttribute('style', 'z-index:9999999');
				}, 300);
			});
		},

		/**
		 * 收到指令
		 */
		onCmd() {
			ivcsCustomer.onCmd(cmdData => {
				console.log('oncmd', cmdData);
				this.showinvteModelView = false;
			});
			ivcsCustomer.onScreenSyncEnd(data => {
				console.log('###onScreenSyncEnd', data);
			});
			// 收到选项判断
			ivcsCustomer.onMakeChoice((cmdId, clientId, fromUser, optionsData) => {
				console.log('onMakeChoice ', cmdId, clientId, fromUser, optionsData);
				this.cmdId = cmdId;
				this.clientId = clientId;
				this.optionsData = optionsData;
			});
			ivcsCustomer.onCancelMakeChoice((cmdId, clientId, fromUser) => {
				console.log('onCancelMakeChoice ', cmdId, clientId, fromUser);
				this.cmdId = '';
			});
		},

		/**
		 * 根据业务场景id呼叫坐席
		 * @param {string} callType 呼叫类型  enum['im'="文本聊天",'audio'='语音通话','video'='视频通话'] 受callAgentProperty类型影响，im只支持人工坐席
		 * @param {string} callAgentProperty 呼叫的坐席类型 enum['all'="人工或AI",'human'="人工",'robot'="AI坐席"]
		 * @param {boolean} showInviteProgressView 是否显示呼叫等待的页面
		 * @param {boolean} showSessionVideoView 是否显示通话中页面
		 * @param {boolean} isScreenSync  是否同屏呼叫
		 * @param {string} callAgentId 呼叫的坐席工号
		 */
		requestSession(callType, callAgentProperty, showInviteProgressView, showSessionVideoView, isScreenSync, callAgentId, callCode) {
			let query = this.$route.query;
			let userData = {
				name: localStorage.getItem('name'),
				userName: localStorage.getItem('name'),
				fullName: sessionStorage.getItem('username'), // 提交资料填写的用户名
				isScreenSyncMode: isScreenSync ? true : false,
				userId: localStorage.getItem('userId'),
				gender: sessionStorage.getItem('gender'),
				formId: this.$store.state.formId,
				idCardNo: sessionStorage.getItem('idcard'),
				phoneNumber: sessionStorage.getItem('mobile'),
				homeAddress: sessionStorage.getItem('address'),
				customerRole: this.customerRole,
				businessflowId: this.businessflowId,
				picture: localStorage.getItem('userPicture'),
				customerLevel: parseInt(this.customerLevel),
				callCode: callCode,
				groups: this.selectCallGroups,
				bizLabelId: this.label,
				virtualAgentType: query.virtualAgentType ? query.virtualAgentType : 'registered'
			};
			if (isScreenSync) {
				showInviteProgressView = showSessionVideoView = false;
			}
			if (callAgentId) {
				console.log('##callAgentId', callAgentId);
				ivcsCustomer.callAgent(
					sessionStorage.getItem('service'), // 业务场景id
					callType,
					callAgentId,
					userData,
					showInviteProgressView,
					showSessionVideoView,
					res => {
						console.log(`'request session success',${JSON.stringify(res)},${new Date()}`);
						this.onCustomerAutoHangup();
						this.onInviteCustomer();
						this.onCmd();
						isScreenSync && ivcsCustomer.startScreenSync();
						isScreenSync && this.$router.push('/link');
						this.loadingStatus = false;
					},
					error => {
						this.loadingStatus = false;
						this.dealWithRequestResponse(error);
					}
				);
			} else {
				ivcsCustomer.callScenario(
					sessionStorage.getItem('service'), // 业务场景id
					callType,
					callAgentProperty,
					userData,
					showInviteProgressView,
					showSessionVideoView,
					res => {
						console.log(`'request session success',${JSON.stringify(res)},${new Date()}`);
						this.onCustomerAutoHangup();
						this.onInviteCustomer();
						this.onCmd();
						isScreenSync && ivcsCustomer.startScreenSync();
						isScreenSync && this.$router.push('/link');
						this.loadingStatus = false;
					},
					error => {
						this.loadingStatus = false;
						this.dealWithRequestResponse(error);
					}
				);
			}
		},

		/**
		 * 处理呼叫的错误码
		 * @param {*} error
		 */
		dealWithRequestResponse(error) {
			console.log(`'request session error',${JSON.stringify(error)},${new Date()}`);
			let message = error.message ? error.message : error;
			switch (error.code) {
				case '601':
					message = '当前业务已完成并通过质检!';
					break;
				case '602':
					message = '当前业务已完成并等待质检!';
					break;
				case '603':
					message = '当前业务正在进行中，请勿重复呼叫!';
					break;
				case '604':
					message = '当前业务正在进行中，请勿重复呼叫！';
					break;
				case '404':
					message = '呼叫的坐席不在线，请稍后再试！';
					break;
				case '406':
					message = '当前非工作日,请您在工作日再次呼叫...';
					break;
				case '407':
					message = '当前非工作时间,请您在工作时间再次呼叫...';
					break;
				case '408':
					message = '您呼叫的业务场景不存在,请查证后再拨...';
					break;
				case '409':
					message = '当前呼叫超过最大并发数,呼叫失败...';
					break;
				case '413':
					message = '坐席正忙，请稍后再试！';
					break;
				case '414':
					message = '坐席正忙，请稍后再试！';
					break;
				case '418':
					message = '未找到所填角色，呼叫失败！';
					break;
				case '420':
					message = '坐席未绑定此业务标签！';
					break;
				case '421':
					message = '业务场景未绑定选择的分组！';
					break;
				case '422':
					message = '呼叫的坐席未绑定当前业务场景！';
					break;
				case '423':
					message = '呼叫的坐席未签入！';
					break;
				case '504':
					message = '坐席工号和业务场景不匹配！';
					break;
				case '101':
					this.isBlacklistedUserShow = true;
					this.alertContent = message;
					break;
				default:
					break;
			}
			if (error.code === '101') {
				// 黑名单
				return;
			}
			this.$Message.error({
				content: message,
				duration: 3,
				top: 0
			});
			this.backLogin();
			ivcsCustomer.destroy();
		},

		// 初始化组件
		initWidget(visitorId, needInitConnect = true, onSuccess, onFailure) {
			let option = {
				debug: true,
				backendUrl: loginUrl,
				org: this.org ? this.org : localStorage.getItem('org'),
				visitorId: localStorage.getItem('userId') ? localStorage.getItem('userId') : '访客' + Math.floor(Math.random() * 10) + 1,
				account: {},
				videoTag: {
					othersControls: true, // 对方video 标签 显示controls
					selfControls: false, // 自己video标签 显示controls
					otherObjectFit: 'cover', // 对方video 设置 object-fit;
					selfObjectFit: 'cover' // 自己video 设置 object-fit;
				},
				bizName: sessionStorage.getItem('bizScenarioName'),
				orgName: '',
				formUrl: formUrl,
				pdfViewerUrl: pdfPreviewUrl,
				countlyAppKey: '8d4ca428d2cf28c3b16fbdfc7d04d86e6fac4ae2',
				countlyHost: 'https://countly.cosee.cc',
				whiteboardInfo: whiteboardInfo,
				token: localStorage.getItem('customer_token')
			};
			if (localStorage.getItem('debug') && localStorage.getItem('debug') == 0) {
				option.debug = false;
			}
			if (!isOpenCountlyLog) {
				option.countlyAppKey = '';
			}
			console.log('ivcsCustomer sdk init options', option);
			if (this.inviteCode) {
				option.account.name = '';
				option.account.password = '';
				option.visitorId = visitorId;
			}
			if (awsFileUrl) {
				option.awsFileUrl = awsFileUrl;
			}
			console.log('init ', option);
			ivcsCustomer.getInstance(option);
			let toolOptions = {
				show_screenSync_stop: true,
				show_screenSync_hangup: true,
				show_layout_change: true,
				show_switch_camera: true,
				show_mute_voice: true,
				show_media_controls: true,
				show_session_hangup: true,
				show_im: true,
				show_inviteOthers: true
			};
			if (localStorage.getItem('layout') && localStorage.getItem('layout') == 0) {
				toolOptions.show_layout_change = false;
			}
			if (localStorage.getItem('microphone') && localStorage.getItem('microphone') == 0) {
				toolOptions.show_mute_voice = false;
			}
			if (localStorage.getItem('camera') && localStorage.getItem('camera') == 0) {
				toolOptions.show_switch_camera = false;
			}
			if (localStorage.getItem('upgrade') && localStorage.getItem('upgrade') == 0) {
				toolOptions.show_media_controls = false;
			}
			ivcsCustomer.initToolBar(toolOptions.show_screenSync_stop, toolOptions.show_screenSync_hangup, toolOptions.show_layout_change, toolOptions.show_switch_camera, toolOptions.show_mute_voice, toolOptions.show_media_controls, toolOptions.show_session_hangup, toolOptions.show_im);
			if (needInitConnect) {
				this.$Spin.show();
				ivcsCustomer.initConnect(
					s => {
						console.log('initConnect s', s);
						this.canCall = true;
						onSuccess && onSuccess();
						this.$Spin.hide();
					},
					e => {
						console.log('initConnect error', e);
						this.$Message.error('初始化链接失败！');
						onFailure && onFailure(e);
						this.$Spin.hide();
					}
				);
			}
			!needInitConnect && onSuccess && onSuccess('ok');
		},

		/**
		 * 呼叫客服
		 */
		videochat(isScreenSync) {
			localStorage.setItem('visittype', 3);
			if (!this.canCall) {
				console.log('isConnect');
				return;
			}
			if (!this.customerRole) {
				this.$Message.error('呼叫时请填写访客角色！');
				return;
			}
			this.loadingStatus = true;
			if (sessionStorage.getItem('bizScenarioName')) {
				let callAgentProperty = 'all';
				if (isScreenSync) {
					callAgentProperty = 'human';
				}
				console.log('request-session callAgentId', this.callAgentId);
				if (this.mode === 'audio') {
					sessionStorage.setItem('callMediaType', 'audio');
					sessionStorage.setItem('receiveMediaType', 'audio');
					this.requestSession('audio', callAgentProperty, true, true, isScreenSync, this.callAgentId);
				} else if (this.mode === 'video') {
					if (this.customerFaceStatus) {
						sessionStorage.setItem('callMediaType', 'video');
					} else {
						sessionStorage.setItem('callMediaType', 'audio');
					}
					if (this.agentFaceStatus) {
						sessionStorage.setItem('receiveMediaType', 'video');
					} else {
						sessionStorage.setItem('receiveMediaType', 'audio');
					}
					let mediaType = 'video';
					if (this.customerFaceStatus != this.agentFaceStatus) {
						mediaType = sessionStorage.getItem('callMediaType') + '-' + sessionStorage.getItem('receiveMediaType');
					}
					console.log('call media type', mediaType);
					this.requestSession(mediaType, callAgentProperty, true, true, isScreenSync, this.callAgentId);
				}
			} else {
				this.$Message.error(this.$t('input.chooseServerType'));
				this.loadingStatus = false;
			}
		},

		/**
		 * 同屏呼叫
		 */
		screensyncchat() {
			// 同屏模式初始为audio
			this.selectMode('audio');
			let isScreenSync = 1;
			// 呼叫客服
			this.videochat(isScreenSync);
		},
		componentSettingBtnClick() {
			this.dialogVisible = true;
		},
		determineBtn(data) {
			this.dialogVisible = false;
			console.log(data);
		},
		cancelComponentSettingBtn() {
			this.dialogVisible = false;
		},
		/**
		 * 根据邀请码加入会话
		 * @param {string} joinMediaType 加入会话的模式，['audio','video']
		 * @param {string} inviteCode 邀请码，由访客或者坐席调用后端接口生成，支持一次性加入或者多次有效加入
		 * @param {object} userData 访客的随路数据，格式如{userName:'',customerRole:''}
		 * @param {function} onSuccess 加入成功，会直接进入会话页面
		 * @param {function} onFailure  加入失败 {code,message} {501:邀请码不存在；502:邀请码已经被使用；503:邀请码还未到开始时间；504:邀请码已过期；505:无效的会话；506:会话已结束；507:通话中存在AI坐席}
		 */
		joinsession() {
			let userData = {
				name: this.inviteUserName,
				userName: this.inviteUserName,
				fullName: this.inviteUserName,
				userId: localStorage.getItem('userId'),
				gender: localStorage.getItem('gender'),
				formId: this.$store.state.formId,
				idCardNo: sessionStorage.getItem('idcard'),
				phoneNumber: sessionStorage.getItem('mobile'),
				homeAddress: sessionStorage.getItem('address'),
				customerLevel: parseInt(this.customerLevel)
			};
			ivcsCustomer.joinSessionWithInviteCode(
				this.mode,
				this.inviteCode,
				userData,
				s => {
					console.log('joinSessionWithInviteCode s', s);
					this.onInviteCustomer();
					this.onCustomerAutoHangup();
					this.onCmd();
				},
				error => {
					console.log('joinSessionWithInviteCode error', error);
					let message = '';
					switch (error.code) {
						case '60022':
							message = '当前设备拒绝了您调用设备摄像头/麦克风的请求';
							break;
						case '60023':
							message = '当前存在其他应用（网页）占用摄像头麦克风资源/启动摄像头麦克风设备失败/当前浏览器摄像头麦克风权限关闭';
							break;
						case '60024':
							message = '当前存在其他应用（网页）占用摄像头麦克风资源/启动摄像头麦克风设备失败/当前浏览器摄像头麦克风权限关闭';
							break;
						case '60025':
							message = '当前设备分辨率与当前通话设置不适配';
							break;
						case '501':
							message = '邀请码不存在!';
							break;
						case '502':
							message = '对不起，该链接不可重复使用!';
							break;
						case '503':
							message = '呼叫码还未到开始时间!';
							break;
						case '504':
							message = '呼叫码已过期!';
							break;
						case '505':
							message = '无效的会话!';
							break;
						case '506':
							message = '会话已结束!';
							break;
						case '507':
							message = '通话存在AI坐席，加入失败!';
							break;
						case '508':
							message = '角色冲突，无法加入会话！';
							break;
						case '601':
							message = '当前业务已完成并通过质检!';
							break;
						case '602':
							message = '当前业务已完成并等待质检!';
							break;
						case '603':
							message = '当前业务正在进行中，请勿重复呼叫!';
							break;
						case '604':
							message = '当前业务正在进行中，请勿重复呼叫！';
							break;
						default:
							message = '业务场景无效！';
							break;
					}
					this.$Message.error(message);
				}
			);
		},
		// 邀请成员 弹框 显示
		inviteVistors() {
			this.showinvteModelView = true;
		},
		// 关闭邀请成员弹框
		colseCancel() {
			this.showinvteModelView = false;
		},
		// 链接生成
		linkGeneration(form, setStatus) {
			console.log(form);
			let bizScenId = sessionStorage.getItem('service');
			let data = {
				bizScenId: bizScenId,
				org: localStorage.getItem('org'),
				type: form.isReuseSwitch === true ? 0 : 1,
				sessionId: this.sessionId,
				customerId: form.userName,
				customerRole: form.role,
				startDate: form.startTime,
				endDate: form.endTime
			};
			createInviteVisitorsCode(data)
				.then(res => {
					if (res.data) {
						console.log(res.data);
						this.createInviteCode = encodeURIComponent(res.data);
						this.$Message.success('链接已生成');
						setStatus('success');
					}
					setTimeout(() => {
						let box = document.querySelector('.ivu-message');
						console.log(box);
						box && box.setAttribute('style', 'z-index:999999999');
					}, 200);
				})
				.catch(err => {
					console.log(err);
					if (err.data && err.data.code === 1301) {
						this.$Message.error('请选择有效的链接有效期');
						console.log(err.data.code, 'code');
						setTimeout(() => {
							setStatus('success');
							setStatus('idle');
						}, 500);
					} else if (err.data && err.data.code === 5003) {
						this.$Message.error(err.data.message);
						console.log(err.data.code, 'code');
						setStatus('idle');
					} else {
						this.$Message.error('链接生成失败');
						setStatus('idle');
					}
					setTimeout(() => {
						let box = document.querySelector('.ivu-message');
						console.log(box);
						box && box.setAttribute('style', 'z-index:999999999');
					}, 200);
				});
		},
		// 响应选项判断
		responseMakeChoice(cmdId, status, responseData, clientId, success, error) {
			ivcsCustomer
				.responseMakeChoice(cmdId, status, responseData, clientId)
				.then(() => {
					success();
				})
				.catch(() => {
					error();
				});
		}
	},

	directives: {
		clickoutside: {
			// eslint-disable-next-line no-unused-vars
			bind(el, binding, vnode) {
				function documentHandler(e) {
					if (el.contains(e.target)) {
						return false;
					}
					if (binding.expression) {
						binding.value(e);
					}
				}
				el.__vueClickOutside__ = documentHandler;
				document.addEventListener('touchend', documentHandler);
			},
			update() {},
			// eslint-disable-next-line no-unused-vars
			unbind(el, binding) {
				document.removeEventListener('touchend', el.__vueClickOutside__);
				delete el.__vueClickOutside__;
			}
		}
	}
};
</script>

<style scoped>
/deep/ .ivu-modal-wrap {
	z-index: 9999999999;
}
.content {
	display: flex;
	flex-direction: column;
	align-items: center;
	width: 100%;
	/* height: 100%; */
	/* position: relative; */
	margin-bottom: 30px;
}

/* .line {
	margin-top: 13px;
	width: 100%;
	height: 7px;
	background: rgba(252, 247, 247, 1);
} */

.btn {
	width: 80%;
	height: 42px;
	/*background:rgba(242,242,242,1);*/
	font-size: 15px;
	font-family: PingFangSC;
	font-weight: 400;
	color: rgba(255, 255, 255, 1);
	line-height: 42px;
	margin-top: 60px;
	border-radius: 21px;
}

.select {
	width: 100%;
	height: 40px;
	/*margin-top: 10px;*/
	/*margin-left: 5%;*/
}

.chooseBtn {
	width: 80%;
	height: 42px;
	line-height: 42px;
	margin-top: 40px;
	border-radius: 21px;
	line-height: 20px;
	background: rgba(100, 202, 171, 1);
	color: rgba(255, 255, 255, 1);
	font-size: 15px;
	font-family: PingFangSC;
}
.setting {
	position: absolute;
	top: 30px;
	right: 34px;
}
.settingImg {
	width: 24px;
}
.settingImg img {
	width: 100%;
}
.settingContent {
	width: 100px;
	height: 100px;
	position: absolute;
	right: -6px;
	z-index: 999;
	background-image: url('../../static/image/toastBack.png');
	background-repeat: no-repeat;
	background-size: 100%;
	font-size: 14px;
	font-family: PingFangSC-Regular, PingFang SC;
	font-weight: 400;
	color: #ffffff;
	padding-top: 10px;
}
.audioContent,
.videoContent {
	height: 42px;
	display: flex;
	justify-content: space-around;
	align-items: center;
}
.audioContent img,
.videoContent img {
	width: 16px;
	height: 16px;
	margin-left: 6px;
}
.horizontalLine {
	width: 100%;
	height: 1px;
	background: #ffffff;
	opacity: 0.45;
}
.audioContent span,
.videoContent span {
	margin-right: 6px;
}
.isActive {
	color: #65c9ac;
}
.toast {
	position: absolute;
	width: 246px;
	height: 190px;
	background: #ffffff;
	border-radius: 16px;
	top: 40%;
	left: 50%;
	transform: translate(-50%, -50%);
	background: #ffffff;
	border-radius: 10px;
	font-size: 16px;
	font-family: PingFangSC-Regular, PingFang SC;
	font-weight: 400;
	color: #999999;
	z-index: 1200;
}
.toastcontent {
	height: 138px;
	padding: 30px 36px 10px 36px;
	border-bottom: 2px solid #eeeeee;
}
.toastagent {
	margin-bottom: 20px;
}
.toastcustomer {
	margin-bottom: 10px;
}
.toastcontent > div {
	display: flex;
	justify-content: space-between;
	align-items: center;
}
.toasttip {
	font-size: 12px;
	font-family: PingFangSC-Regular, PingFang SC;
	font-weight: 400;
	color: #c7c7c7;
	display: flex;
}
.toasttip img {
	width: 12px;
}
.toastfooter {
	height: 46px;
	display: flex;
	justify-content: center;
	align-items: center;
}
.toastfooter span {
	width: 48%;
	line-height: 46px;
}
.cancel {
	border-right: 2px solid #eeeeee;
}
.preserve {
	color: #65c9ac;
}
.backDemon {
	position: fixed;
	left: 0px;
	top: 0px;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 1);
	width: 100%; /*宽度设置为100%，这样才能使隐藏背景层覆盖原页面*/
	height: 100%;
	filter: alpha(opacity = 60); /*设置透明度为60% */
	opacity: 0.6; /*非IE浏览器下设置透明度为60%*/
	z-index: 999;
}
.invite-code {
	margin-top: 20px;
}
.label_view {
	margin-top: 20px;
	margin-bottom: 20px;
}
.request_setting_view {
	margin-left: -30px;
	margin-bottom: 15px;
	z-index: 0;
}
</style>
<style>
.ivu-spin-show-text .ivu-spin-dot {
	display: inline-block;
}
.demo-spin-icon-load {
	animation: ani-demo-spin 1s linear infinite;
}
@keyframes ani-demo-spin {
	from {
		transform: rotate(0deg);
	}
	50% {
		transform: rotate(180deg);
	}
	to {
		transform: rotate(360deg);
	}
}
</style>
